package middleware

import (
	"api/internal/types"
	jwt "github.com/golangblogs/gojwt"
	"github.com/zeromicro/go-zero/rest/httpx"
	"net/http"
	"strconv"
)

type UserAgentMiddleware struct {
}

func NewUserAgentMiddleware() *UserAgentMiddleware {
	return &UserAgentMiddleware{}
}

func (m *UserAgentMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		token := r.Header.Get("token")
		if token == "" {
			resp := &types.Response{
				Code:    500,
				Message: "未登录",
				Data:    nil,
			}
			httpx.OkJsonCtx(r.Context(), w, resp)
			return
		}

		newJwt := jwt.NewJWT("2301a")
		parseToken, err := newJwt.ParseToken(token)
		if err != nil {
			resp := &types.Response{
				Code:    500,
				Message: err.Error(),
				Data:    nil,
			}
			httpx.OkJsonCtx(r.Context(), w, resp)
			return
		}
		r.ParseForm()
		r.Form.Set("userId", strconv.Itoa(int(parseToken.ID)))
		next(w, r)
	}
}
